﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhotoGallery.Core.Business;
using System.IO;
using PhotoGallery.Infrastructure;
using System.Web;


namespace PhotoGallery.Models.Model.Home
{
    /// <summary>
    /// 这是文件管理的Wrapper
    /// </summary>
    [Serializable]
    public class HomeDetailModel
    {
        #region Field & Property

        /// <summary>
        /// 文件节点
        /// </summary>
        public PicNode PicNode { get; protected set; }

        /// <summary>
        /// 文件夹描述信息
        /// </summary>
        public FolderDesc FolderDesc { get; protected set; }

        /// <summary>
        /// 文件内子文件信息
        /// </summary>
        public IList<FileInfo> FileInfos { get; protected set; }

        /// <summary>
        /// 文件夹中子文件夹信息
        /// </summary>
        public IList<DirectoryInfo> DictionaryInfos { get; protected set; }

        #endregion

        #region Constructor

        protected HomeDetailModel()
        {

        }

        public HomeDetailModel(PicNode node, FolderDesc desc)
        {
            if (node == null)
                throw new ArgumentException("文件夹节点不能为空！");
            this.PicNode = node;
            this.FolderDesc = desc;


            // 核心代码如下：根据文件的路径查找文件信息

            DirectoryInfo dir = new DirectoryInfo(FileConfiguration.FullPath + this.PicNode.Path.Replace("/", @"\"));

            if (!dir.Exists)
                dir.Create();

            // 而后将不在文件夹和文件都剔除
            this.FileInfos = dir.GetFiles("*.*");


            DirectoryInfo tmp = new DirectoryInfo(FileConfiguration.FullPath);

            foreach (var f in this.FileInfos)
            {
                string result = f.FullName.Substring(tmp.FullName.Length, f.FullName.Length - tmp.FullName.Length);
                if (!string.IsNullOrEmpty(result))
                    result = result.Replace("\\", "/");
                FileRecord record = FileRecord.Find(result);
                if (record != null)
                {
                    this.FileInfos = this.FileInfos.ToList();
                    this.FileInfos.Remove(f);
                }
            }


            this.DictionaryInfos = dir.GetDirectories("*.*");

            foreach (var d in this.DictionaryInfos)
            {
                string result = d.FullName.Substring(tmp.FullName.Length, d.FullName.Length - tmp.FullName.Length);
                if (!string.IsNullOrEmpty(result))
                    result = result.Replace("\\", "/");
                PicNode folder = PicNode.Find(result, 1);
                if (folder != null)
                {
                    this.DictionaryInfos = this.DictionaryInfos.ToList();
                    this.DictionaryInfos.Remove(d);
                }
            }

        }

        #endregion


    }
}
